<template>
  <div class="login-container">
    <div class="left">
      <div class="title-box">
        <img src="@/assets/img/login_icon.png" alt="" />
        <span class="title">黑马面面</span>
        <span class="line"></span>
        <span class="sub-title">用户登录</span>
      </div>
      <!--
        model:绑定的模型，他这个里面是什么属性，根据业务逻辑来
        rules:校验规则
        ref:拿到当前的el-form组件
      -->
      <el-form
        class="login-form"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
      >
        <!-- prop要跟ruleForm和rules中的名字保持一致，它的作用是校验和重置 -->
        <el-form-item prop="phone">
          <el-input
            v-model="ruleForm.phone"
            placeholder="请输入手机号"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
          ></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="16">
            <el-form-item prop="code">
              <el-input
                v-model="ruleForm.code"
                placeholder="请输入验证码"
                prefix-icon="el-icon-key"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col style="margin-left:10px;" :span="7">
            <img
              @click="changeLoginCaptcha"
              style="width:100%;height:40px;"
              :src="loginCaptcha"
              alt=""
            />
          </el-col>
        </el-row>
        <el-form-item prop="checked">
          <!-- 如果写在el-checkbox里面的文字，会跟着它一起高亮 -->
          <el-checkbox v-model="ruleForm.checked"></el-checkbox>
          我已阅读并同意
          <el-link type="primary" href="http://www.baidu.com" target="__blank"
            >用户协议</el-link
          >和<el-link type="primary" href="http://www.jd.com" target="__blank"
            >隐私条款</el-link
          >
        </el-form-item>
        <el-form-item>
          <el-button style="width:100%;" @click="login" type="primary"
            >登 录</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button style="width:100%;" type="primary" @click="regester"
            >注 册</el-button
          >
        </el-form-item>
        <!-- <el-form-item>
          <el-button style="width:100%;" type="primary" @click="routerTest"
            >测试</el-button
          >
        </el-form-item> -->
      </el-form>
    </div>
    <div class="right">
      <!-- @代表src -->
      <img src="@/assets/img/login_bg.png" alt="" />
    </div>
    <!-- 注册子组件 -->
    <register ref="registerRef" />
  </div>
</template>

<script>
// 按需导入，{} 是语法标识，不是对象
import { saveToken } from '@/utils/token'
import register from './register'
export default {
  name: 'Login',
  components: {
    register
  },
  data () {
    return {
      loginCaptcha: `${process.env.VUE_APP_BASEURL}/captcha?type=login`,
      ruleForm: {
        phone: '18511111111', // 手机号
        password: '12345678', // 密码
        code: '', // 验证码
        checked: true // 是否选中同意协议
      },
      rules: {
        phone: [
          {
            /**
             * rule：规则
             * value: 输入的值
             * callback：回调，决定是否校验通过
             */
            validator: (rule, value, callback) => {
              if (!value) return callback(new Error('手机号不能为空'))

              const reg = /^1[3456789][0-9]{9}$/
              if (!reg.test(value)) return callback(new Error('手机号不合法'))

              // 能来到这里肯定是成功了，callback也要执行
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空',
            trigger: 'blur'
          }
        ],
        checked: [
          {
            validator: (rule, value, callback) => {
              value ? callback() : callback(new Error('必须勾选用户协议'))
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    changeLoginCaptcha () {
      this.loginCaptcha = `${
        process.env.VUE_APP_BASEURL
      }/captcha?type=login&t=${new Date() - 0}`
    },
    login () {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return

        /** 使用promise方式 */
        /**
        this.$axios.post('/login', this.ruleForm).then(res => {
          if (res.data.code === 200) {
            this.$message.success('登录成功~')

            // 保存token到本地
            localStorage.setItem('heimamm64-token', res.data.data.token)

            // 跳转到layout页面
            this.$router.push('/layout')
          } else {
            // 没成功
            this.$message.error(res.data.message)

            // 刷新验证码
            this.changeLoginCaptcha()
          }
        })
         */
        // await 后面接的就是promise对象
        const res = await this.$axios.post('/login', this.ruleForm)

        if (res.code === 200) {
          this.$message.success('登录成功~')

          // 保存token到本地
          // localStorage.setItem('heimamm64-token', res.data.token)
          saveToken(res.data.token)

          // 跳转到layout页面
          this.$router.push('/layout')
        } else {
          // 没成功
          this.$message.error(res.message)

          // 刷新验证码
          this.changeLoginCaptcha()
        }
      })
    },
    regester () {
      this.$refs.registerRef.dialogVisible = true
    }
    // routerTest () {
    //   // this.$router.push('/newsdetail?id=10001')
    //   this.$router.push('/newsdetail/10003/lisi')
    // }
  }
}
</script>

<style lang="less">
.login-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background: linear-gradient(225deg, #1493fa, #01c6fa);

  .left {
    width: 478px;
    height: 550px;
    background: #f5f5f5;
    padding: 48px;
    .title-box {
      display: flex;
      align-items: center;
      img {
        width: 22px;
        height: 17px;
        margin-right: 16px;
      }
      .title {
        font-size: 24px;
        margin-right: 14px;
      }
      .line {
        width: 1px;
        background-color: #c7c7c7;
        height: 27px;
        margin-right: 12px;
      }
      .sub-title {
        font-size: 22px;
      }
    }
    .login-form {
      margin-top: 29px;
    }
  }
}
</style>
